import $ from "jquery";
import { message } from 'antd'
export function str_to_base64(str) {
  // 对字符串进行编码
  var encode = encodeURI(str);
  // 对编码的字符串转化base64
  var base64 = btoa(encode);
  return base64;
}
export const getUploadImageWidthAndHeight = async url => {
  //这里返回的是一个promise
  var result = [];
  await new Promise(function (resolve, reject) {
    var img = new Image();
    img.src = url;
    img.onload = function () {
      result[0] = img.width;
      result[1] = img.height;
      resolve(result);
    };
  });
  return result
};
export const getDivWidthAndHeight = id => {//返回数值
  let img = document.getElementById(id);
  let result = [];
  result.push(window.getComputedStyle(img).width);
  result.push(window.getComputedStyle(img).height);
  result[0] = result[0].split("px")[0];
  result[1] = result[1].split("px")[0];
  return result;
};
export // base64转字符串
  function base64_to_str(base64) {
  // 对base64转编码
  var decode = atob(base64);
  // 编码转字符串
  var str = decodeURI(decode);
  return str;
}

export let deselect_checkbox_border_immediately_without_checking = () => {
  $(function () {
    for (let i = 0; i < $(".check_box").find("span:even").length; i++) {
      if (
        $(".check_box")
          .find("span:even")
        [i].className.split(" ")[1] === "ant-checkbox-checked"
      ) {
        $(".check_box").find("span:even")[i].childNodes[1].style.border =
          "1px solid #1890ff";
      } else {
        $(".check_box").find("span:even")[i].childNodes[1].style.border =
          "1px solid #d9d9d9";
      }
    }
  });
};

export let add_delete_button_function_to_delete_box = class_name => {
  $(function () {
    $(`.${class_name} .ant-modal-content`).append(`<div class="delete_icon_class"}></div`);
    for (
      let i = 0;
      i <
      $(`.${class_name} .delete_icon_class`)
        .siblings()
        .find("span").length;
      i++
    ) {
      if (
        $(`.${class_name} .delete_icon_class`)
          .siblings()
          .find("span")[i].innerHTML === "取 消"
      ) {
        $(`.${class_name} .delete_icon_class`).click(function () {
          //用于给按钮增加删除事件
          $(`.${class_name} .delete_icon_class`)
            .siblings()
            .find("span")
          [i].click();
        });
      }
    }
  });
};
export const delete_button_style = class_name => {
  $(function () {
    $(`.${class_name}`).removeAttr("style");
  });
};
//统一按钮默认样式
export const stroke_in_and_out_style = () => {
  $(function () {
    //按钮默认样式，划入划出样式
    $("button").each(function () {
      $(this).addClass("button_class");
      if ($(this).attr('disabled') === 'disabled') {
      } else {
        $(this).on("mouseenter", function () {
          $(this).css({
            border: "1px solid rgba(0,124,220,1)",
            color: "rgba(0,124,220,1)"
          });
        });
        $(this).on("mouseleave", function () {
          $(this).css({
            border: "1px solid rgba(0,163,255,1)",
            color: "rgba(0,163,255,1)"
          });
        });
      }
    });
  });
};
//highlighting
export const highlighting = class_name => {
  $(`.${class_name}`).each(function () {
    $(this).on("click", function () {
      var original_style = $(this).css("color");
      $(this).css({ color: "#00a3ff" });
      $(this)
        .siblings()
        .css({ color: original_style });
    });
  });
};
//数组去重
export const unique = (arr) => {
  let b = []
  for (let i = 0; i < arr.length; i++) {
    if (b.indexOf(arr[i]) == -1) {
      b.push(arr[i])
    }
  }
  return b
}
//对象深拷贝
export function deep_copy(obj) {
  var result = Array.isArray(obj) ? [] : {};
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        result[key] = deep_copy(obj[key]);   //递归复制
      } else {
        result[key] = obj[key];
      }
    }
  }
  return result;
}

export const img_format_size = (file) => {//上传图片的格式校验
  const fileType = "image/pngimage/jpgimage/jpeg";
  if (fileType.indexOf(file.type) < 0) {
    message.info("请上传正确的图片格式");
    return false;
  } else if (file.size > 5 * 1024 * 1024) {
    message.info("图片不能大于5MB");
    return false;
  } else {
    return true
  }
}
//图片懒加载
export const picture_lazy_load = (ul_class_name, img_class_name, distance_to_scroll) => {
  $(function () {
    lazy_load();
    // 当页面开始滚动的时候，遍历图片，如果图片出现在视窗中，就加载图片
    var clock; //函数防抖
    $(`.${ul_class_name}`).on('scroll', function () {
      if (clock) {
        clearTimeout(clock);
      }
      clock = setTimeout(function () {
        lazy_load()
      }, 200)
    });
    function lazy_load() {
      $(`.${ul_class_name} .${img_class_name}`).not('[data-isLoading]').each(function () {
        if (isShow($(this))) {
          console.log('load')
          loadImg($(this));
        }
      })
    }
    // 判断图片是否出现在视窗的函数
    function isShow($node) {
      if ($node.offset().top - distance_to_scroll <= $(`.${ul_class_name}`).height()) {
        return true
      } else {
        return false
      }
    }
    // 加载图片的函数，就是把自定义属性data-src 存储的真正的图片地址，赋值给src
    function loadImg($img) {
      $img.css({ 'background-image': `url(${$img.attr('data-src')})` })
      // 已经加载的图片，我给它设置一个属性，值为1，作为标识
      // 弄这个的初衷是因为，每次滚动的时候，所有的图片都会遍历一遍，这样有点浪费，所以做个标识，滚动的时候只遍历哪些还没有加载的图片
      $img.attr('data-isLoading', 1);
    }
    // 一开始没有滚动的时候，出现在视窗中的图片也会加载
  })
}
export function formatDate(time) { //如果记得时间戳是毫秒级的就需要*1000 不然就错了记得转换成整型
  let now = new Date(time * 1000)
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var date = now.getDate();
  var hour = now.getHours();
  var minute = now.getMinutes();
  var second = now.getSeconds();
  return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}

